import { IDictionariesItem } from "@/service/type";
import { FC } from "@tarojs/taro";
import { View } from "@tarojs/components";
import { AtButton, AtDrawer } from "taro-ui";
import styles from "./index.module.less";
import { useEffect, useState } from "react";
import { useMount } from "ahooks";

interface IProps {
  value: string[];
  list: IDictionariesItem[];
  drawerVisible: boolean;
  /** 多选 */
  multiple?: boolean;
  setDrawerVisible: (boolean) => void;
  onSelectedLabelItem: (data: IDictionariesItem[]) => void;
}

const DrawerPanel: FC<IProps> = (props) => {
  const [selectedLabels, setSelectedLabels] = useState<IDictionariesItem[]>([]);
  const {
    value,
    list,
    drawerVisible,
    multiple,
    setDrawerVisible,
    onSelectedLabelItem,
  } = props;

  useEffect(() => {
    const labels = list.filter((item) => value.indexOf(item.value) !== -1);
    setSelectedLabels([...labels]);
  }, [value, list]);

  /** 是否高亮标签 */
  function isActive(target) {
    const result = value.indexOf(target.value) !== -1;
    return result
      ? `${styles["item"]} ${styles["active"]}`
      : `${styles["item"]}`;
  }

  function onSelected(item: IDictionariesItem) {
    if (multiple) {
      const index = selectedLabels.indexOf(item);
      index !== -1
        ? selectedLabels.splice(index, 1)
        : selectedLabels.push(item);
      return onSelectedLabelItem([...selectedLabels]);
    }
    onSelectedLabelItem([item]);
  }

  return (
    <>
      {/* 选择面板 */}
      <AtDrawer
        show={drawerVisible}
        mask
        right
        onClose={() => setDrawerVisible(false)}
      >
        <View className={styles["list-wrapper"]}>
          {list.map((item) => (
            <View className={isActive(item)} onClick={() => onSelected(item)}>
              {item.label}
            </View>
          ))}
        </View>
      </AtDrawer>
    </>
  );
};

export default DrawerPanel;
